﻿#ifndef TCPSERVER_H
#define TCPSERVER_H

#include <QHash>
#include <QThread>
#include <QTcpServer>
#include <QTcpSocket>

#define MAX_TCP_CLIENT 5

class TcpServer : public  QObject
{
    Q_OBJECT
public:
    explicit TcpServer(QObject *parent = nullptr);

    QList<QString> getClientList() { return m_clientObjList.keys(); }

    void cleanup();
    bool listen(const QHostAddress &ip, int port);
    bool isListening() { return m_server->isListening(); }
    bool stopListen();
    void deleteClient(const QString &clientStr);

    void resetCNT() { m_sendMsgLenCnt = m_revMsgLenCnt = 0; }

    void sendMsgToClient(const QString &clientStr, const QByteArray &msg);

signals:
    void sigClientUpdate();
    void sigReadMsg(const QString &ip, const QByteArray& msg);
    void sigCNTUpdate(int send_len, int rev_len);

    void sigSystemLog(const QString &log_msg);

private slots:
    void onNewConnection();
    void onDisconnected();
    void onMessageCTRL();

private:
    int m_sendMsgLenCnt;    ///< 发送的字符长度计数
    int m_revMsgLenCnt;     ///< 收到的字符长度计数

    QTcpServer *m_server;
    QHash<QString, QTcpSocket*> m_clientObjList;

};

#endif // TCPSERVER_H
